package main

import (
	"context"
	"github.com/gin-gonic/gin"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
	"net/http"
	"time"
)

type User struct {
	ID       string `json:"id,omitempty" bson:"_id,omitempty"`
	Name     string `json:"name,omitempty" bson:"name,omitempty"`
	Email    string `json:"email,omitempty" bson:"email,omitempty"`
	Password string `json:"password,omitempty" bson:"password,omitempty"`
}

var client *mongo.Client

func init() {
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()

	clientOptions := options.Client().ApplyURI("mongodb://localhost:27017")
	client, _ = mongo.Connect(ctx, clientOptions)
}

func main() {
	router := gin.Default()

	router.GET("/users", func(c *gin.Context) {
		users := []User{}
		collection := client.Database("test").Collection("users")
		cur, err := collection.Find(context.Background(), bson.M{})
		if err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"error": "查询用户失败"})
			return
		}
		defer cur.Close(context.Background())
		for cur.Next(context.Background()) {
			var user User
			err := cur.Decode(&user)
			if err != nil {
				c.JSON(http.StatusInternalServerError, gin.H{"error": "解码用户失败"})
				return
			}
			users = append(users, user)
		}
		c.JSON(http.StatusOK, users)
	})

	router.POST("/users", func(c *gin.Context) {
		var user User
		if err := c.ShouldBindJSON(&user); err != nil {
			c.JSON(http.StatusBadRequest, gin.H{"error": "无效的输入"})
			return
		}
		collection := client.Database("test").Collection("users")
		res, err := collection.InsertOne(context.Background(), user)
		if err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"error": "创建用户失败"})
			return
		}
		user.ID = res.InsertedID.(string)
		c.JSON(http.StatusOK, user)
	})

	router.PUT("/users/:id", func(c *gin.Context) {
		var user User
		if err := c.ShouldBindJSON(&user); err != nil {
			c.JSON(http.StatusBadRequest, gin.H{"error": "无效的输入"})
			return
		}
		id := c.Param("id")
		filter := bson.M{"_id": id}
		update := bson.M{
			"$set": user,
		}
		collection := client.Database("test").Collection("users")
		res, err := collection.UpdateOne(context.Background(), filter, update)
		if err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"error": "更新用户失败"})
			return
		}
		if res.MatchedCount == 0 {
			c.JSON(http.StatusNotFound, gin.H{"error": "找不到用户"})
			return
		}
		c.JSON(http.StatusOK, user)
	})

	router.DELETE("/users/:id", func(c *gin.Context) {
		id := c.Param("id")
		filter := bson.M{"_id": id}
		collection := client.Database("test").Collection("users")
		res, err := collection.DeleteOne(context.Background(), filter)
		if err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"error": "删除用户失败"})
			return
		}
		if res.DeletedCount == 0 {
			c.JSON(http.StatusNotFound, gin.H{"error": "找不到用户"})
			return
		}
		c.JSON(http.StatusOK, gin.H{"message": "删除成功"})
	})

	router.Run(":8090")
}
